package com.test.controller;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.test.R;


/**
 * 按钮选择
 */
public class RadioButtonActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.button_demo);//把该类放在容器中
        Button button = findViewById(R.id.btnSubmit);//查找定义的buttonId
        final RadioGroup radioGroup = findViewById(R.id.RadioGroup);//查找选择组id

        //第一种获得单选按钮值得方法为radioGroup设置一个监听器: setOnCheckedChangeListener
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                RadioButton radioButton = findViewById(checkedId);
                Toast.makeText(getApplicationContext(), "你选了: " + radioButton.getText(), Toast.LENGTH_LONG).show();
            }
        });

        //第二种。把显示选择信息与button绑定在一起，设置点击事件
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                for (int i = 0; i < radioGroup.getChildCount(); i++) {
                    RadioButton radioButton = (RadioButton) radioGroup.getChildAt(i);
                    if (radioButton.isChecked()) {
                        Toast.makeText(getApplicationContext(), "你选择的是: " + radioButton.getText(), Toast.LENGTH_LONG).show();
                        break;
                    }
                }
            }
        });
    }
}
